var websocket = null;
var name="null";
var id=0;
function getCookie(sName)
{
	
var aCookie = document.cookie.split(";");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
return null;
}
function init()
        {
	
           getname();
            }
function getname(){
	name=GetRequestName();
	connect(name);
}
function connect(nikname){
   
    id=getCookie("user");
    if ('WebSocket' in window) {
    	let url="ws://172.7.41.152:8088/blogserver/websocket/"+nikname;
        websocket = new WebSocket(url);
       
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

   
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

  
    websocket.onopen = function () {
    alert("WebSocket连接成功");
    }

//    <div class="order"><div class="orderimg"><img  class="headimg" src="images/26.jpg"></div>
//    <div class="orderchat">你好</div>
//</div>
//<div class="other"><div class="otherimg"><img  class="headimg" src="images/26.jpg"></div>
//           <div class="othername">
//                name
//            </div>    
//    <div class="otherchat"> 你好</div>
//</div>
    websocket.onmessage = function (event) {
        let json=JSON.parse(event.data);
        document.getElementById('chating').innerHTML=document.getElementById('chating').innerHTML+"<div class='other'><div class='otherimg'><img  class='headimg' src='usermessageadmin.servlet?param=getIcon&id="+json.obid+"'></div><div class='othername'>"+json.ob+"</div><div class='otherchat'>"+json.message+"</div></div>";
    }

   
    websocket.onclose = function () {
        alert("WebSocket连接关闭");
    }

    
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    
}
   
   

    
    function closeWebSocket() {
        websocket.close();
    }

    
    function send() {
        var message = document.getElementById('textbox').value;
        document.getElementById('chating').innerHTML=document.getElementById('chating').innerHTML+"<div class='order'><div class='orderimg'><img  class='headimg' src='usermessageadmin.servlet?param=getIcon&id="+id+"'></div><div class='orderchat'>"+message+"</div></div>";
        var op = "all";
        if(op==""){
        	op="all";
        }
        var map={};
       map['op']=op;
       map['message']=message;
       map['ob']=name
       map['obid']=id;
       jsonstr=JSON.stringify(map);
        websocket.send(jsonstr);
    }
    function GetRequestName() {
  	  
  	  var url = location.search; 
  	   var theRequest = new Object();
  	   if (url.indexOf("?")!= -1) {
  	     url=url.substr(url.indexOf("name=")+5);
  	   }
  	   return url;
  	}
    window.addEventListener("load",init,false);